const db = require('../db');

const Warehouse = {
    // 创建仓库
    async create(data) {
        const {
            name,
            projectId,
            projectName,
            location,
            manager,
            contact,
            area,
            capacity,
            remark,
            materialCount,
            status
        } = data;

        const [result] = await db.execute(
            `INSERT INTO warehouse 
            (name, projectId, projectName, location, manager, contact, area, capacity, remark, materialCount, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [name, projectId, projectName, location, manager, contact, area, capacity, remark, materialCount || 0, status || 1]
        );
        return result;
    },

    // 获取所有仓库
    async getAll() {
        const [rows] = await db.execute(`SELECT * FROM warehouse WHERE status != 2`);
        return rows;
    },

    // 根据 ID 获取仓库
    async getById(id) {
        const [rows] = await db.execute(`SELECT * FROM warehouse WHERE id = ?`, [id]);
        return rows[0];
    },

    // 更新仓库
    async update(id, data) {
        const {
            name,
            projectId,
            projectName,
            location,
            manager,
            contact,
            area,
            capacity,
            remark,
            materialCount,
            status,
            ended_at
        } = data;

        const [result] = await db.execute(
            `UPDATE warehouse SET
                name = ?, 
                projectId = ?, 
                projectName = ?, 
                location = ?, 
                manager = ?, 
                contact = ?, 
                area = ?, 
                capacity = ?, 
                remark = ?, 
                materialCount = ?, 
                status = ?, 
                ended_at = ?
             WHERE id = ?`,
            [name, projectId, projectName, location, manager, contact, area, capacity, remark, materialCount, status, ended_at, id]
        );
        return result;
    },

    // 删除仓库（软删除）
    async remove(id) {
        const [result] = await db.execute(
            `UPDATE warehouse SET status = 2 WHERE id = ?`,
            [id]
        );
        return result;
    },
};

module.exports = Warehouse;
